# -*- coding: utf8 -*-
import os
import jinja2
import webapp2
import json
import logging

from random import randint
from google.appengine.api import users
from player import *

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'])


class PlayerEmailHandler(webapp2.RequestHandler):
    def get_player(self):
        player_email = self.request.get("email")
        player = Player.get_by_email(player_email)
        if player is None:
            self.error(404)
            self.response.write('ERROR 404: Player %s not found' %
                                player_email)
            return None
        return player


class ProcessAuth(webapp2.RequestHandler):
    def get(self):
        email = ''
        nick = ''
        user = users.get_current_user()
        if user:
            player = Player.get_by_email(user.email())
            if player is None:
                player = Player(email=user.email(),
                                nickname=user.nickname(),
                                words=[])
                player.put()

            email = player.email
            nick = player.nickname

        none = None
        template = JINJA_ENVIRONMENT.get_template('user_cabinet.html')
        self.response.write(template.render({
            "email": email,
            "nick": nick,
            "logout": users.create_logout_url("/"),
            "login": users.create_login_url("/user_cabinet.html")
        }))


class EditUser(webapp2.RequestHandler):
    def get(self):
        email = ''
        nick = ''
        pin = 0000
        words = ''
        user = users.get_current_user()
        player = Player.get_by_email(user.email())

        email = player.email
        nick = player.nickname
        pin = player.pin_code
        words = '\n'.join(player.words)
        template = JINJA_ENVIRONMENT.get_template('edit_user.html')
        self.response.write(template.render({
            "email": email,
            "nick": nick,
            "pin": pin,
            "words": words
        }))


class ProcessGeneratingPin(PlayerEmailHandler):
    def post(self):
        player = self.get_player()
        if player is None:
            return
        player.pin_code = randint(1000, 9999)
        player.put()
        self.redirect("/edit_user.html")


class ProcessEditingPlayer(PlayerEmailHandler):
    def post(self):
        player = self.get_player()
        if player is None:
            return
        name = self.request.get("name")
        words_sring = self.request.get("words")
        words = words_sring.split()
        player.nickname = name
        player.words = words
        player.put()
        self.redirect("/edit_user.html")
